package com.gingko.duominuo.utils

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.gingko.duominuo.R

class FragmentSwitchManager(
    private val fragmentManager: FragmentManager,
    private val fragments: List<Fragment>,
    private val fragmentContentId: Int
) {
    private var currentTab // 当前Tab页面索引
            = 0
    private var needAnim = false
    fun selectFragment(position: Int) {
        for (i in fragments.indices) {
            if (position == i) {
                val fragment = fragments[i]
                val ft = obtainFragmentTransaction(i)
                fragments[currentTab].onStop() // 暂停当前tab
                if (fragment.isAdded) {
                    fragment.onStart() // 启动目标tab的fragment onStart()
                } else {
                    ft.add(fragmentContentId, fragment)
                    ft.commit()
                }
                showTab(i) // 显示目标tab
                return
            }
        }
    }

    /**
     * 切换tab
     *
     * @param idx
     */
    private fun showTab(idx: Int) {
        for (i in fragments.indices) {
            val fragment = fragments[i]
            val ft = obtainFragmentTransaction(idx)
            if (idx == i) {
                ft.show(fragment)
            } else {
                ft.hide(fragment)
            }
            ft.commit()
        }
        currentTab = idx // 更新目标tab为当前tab
    }

    fun setNeedAnim(needAnim: Boolean) {
        this.needAnim = needAnim
    }

    /**
     * 获取一个带动画的FragmentTransaction
     *
     * @param index
     * @return
     */
    private fun obtainFragmentTransaction(index: Int): FragmentTransaction {
        val ft = fragmentManager.beginTransaction()
        if (needAnim) {
            // 设置切换动画
            if (index > currentTab) {
                ft.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left)
            } else {
                ft.setCustomAnimations(R.anim.slide_in_from_left, R.anim.slide_out_to_right)
            }
        }
        return ft
    }

    init {
        // 默认显示第一页
        val ft = fragmentManager.beginTransaction()
        ft.add(fragmentContentId, fragments[0])
        ft.commitAllowingStateLoss()
    }
}